import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:ball_lion/module/match/list/lq_focus_logic.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/entity/match/lq_list_entity.dart';
import 'package:ball_lion/entity/match/zq_list_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/card.dart';

class LqMatchCell extends StatefulWidget {
  final LqListEntity match;
  const LqMatchCell(this.match, {super.key});

  @override
  State<LqMatchCell> createState() => _LqMatchCellState();
}

class _LqMatchCellState extends State<LqMatchCell> {
  LqConfig config = Get.find<ConfigService>().lqConfig;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Utils.onEvent('match_view', params: {'match_id': widget.match.id});
        Get.toNamed(
          Routes.lqMatchDetail,
          arguments: widget.match.id,
          // parameters: {"roomId": widget.match.roomId.hasValue?"${widget.match.roomId}":''}
        );
      },
      child: Block(
          cardStyle: CardStyle(
            margin: EdgeInsets.only(
                bottom: widget.match.lastMatchInDay ? 0 : 8,
                left: 8,
                right: 8,
                top: widget.match.showTopSpace ? 8 : 0),
            padding: const EdgeInsets.all(8),
          ),
          child: Column(children: [
            top(),
            const SizedBox(height: 10),
            middle(),
            const SizedBox(height: 4),
            if (widget.match.hasBegin()) bottom().paddingOnly(top: 2)
          ])),
    );
  }

  top() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        Flexible(
          fit: FlexFit.tight,
          flex: 2,
          child: Row(
            textBaseline: TextBaseline.alphabetic,
            crossAxisAlignment: CrossAxisAlignment.baseline,
            children: [
              QsText(
                widget.match.leagueName ?? '',
                color: widget.match.leagueColor == null
                    ? Colours.grey66
                    : HexColor(widget.match.leagueColor!),
                fontSize: 11,
              ),
              const SizedBox(width: 4),
              QsText(
                DateTimeUtils.formatDateString(
                    widget.match.matchTime!, 'HH:mm'),
                color: Colours.grey66,
                fontSize: 11,
              ),
              const SizedBox(width: 4),
              if (config.lqList3 == 1)
                QsText(widget.match.jcNo ?? '',
                    needCenter: true, color: Colours.grey66, fontSize: 11)
            ],
          ),
        ),
        Flexible(
          flex: 1,
          child: Center(
              child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              QsText('${widget.match.show}',
                  color: HexColor(widget.match.color!), fontSize: 11),
              if (widget.match.statusId == '2' ||
                  widget.match.statusId == '4' ||
                  widget.match.statusId == '6' ||
                  widget.match.statusId == '8' ||
                  widget.match.statusId == '9')
                QsText('\'', color: HexColor(widget.match.color!), fontSize: 11)
                    .animate(
                      onPlay: (controller) => controller.repeat(),
                    )
                    .fade(duration: 1000.ms)
            ],
          )),
        ),
        Flexible(
            flex: 2,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                label(
                    show: widget.match.intelligence == 1,
                    name: Constant.baoliao,
                    color: Colours.main),
                label(
                    show: widget.match.planCnt.hasValue,
                    name: Constant.guandian,
                    extra:
                        "${widget.match.planCnt! > 99 ? "99+" : widget.match.planCnt}",
                    color: const Color(0xFF2469FD)),
                label(
                    show: widget.match.ai ?? false,
                    name: Constant.model,
                    color: const Color(0xFFF139BE)),
              ],
            )),
      ],
    );
  }

  middle() {
    return Row(
      // mainAxisSize: MainAxisSize.max,
      children: [
        GestureDetector(
            onTap: () async {
              if (User.basketballFocuses.isFocus(widget.match.id!)) {
                Utils.onEvent('bspdlq', params: {'bspdlq': '0'});
                await User.basketballFocuses.unFocus(widget.match.id!);
              } else {
                Utils.onEvent('bspdlq', params: {'bspdlq': '1'});
                await User.basketballFocuses.focus(widget.match.id!);
              }
              setState(() {});
              try {
                Get.find<LqFocusLogic>().getMatch();
              } catch (e) {}
              // matchInterestController.getMatch();
            },
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 4),
              child: User.basketballFocuses.isFocus(widget.match.id!)
                  ? Image.asset(Utils.getImgPath("match_focus.png"),
                      color: Colours.main, width: 18, height: 18)
                  : Image.asset(Utils.getImgPath("match_unfocus.png"),
                      color: Colors.grey,
                      width: 18,
                      height: 18,
                      fit: BoxFit.scaleDown),
            )),
        Container(width: 8),
        Expanded(
          child: Column(
            children: [team(false), const SizedBox(height: 6), team(true)],
          ),
        ),
        teamRight(),
        if (widget.match.live ?? false)
          Padding(
            padding: const EdgeInsets.only(left: 8),
            child: Image.asset(
              Utils.getImgPath("live_video_icon.png"),
              width: 18,
              height: 14,
            ),
          )
        else if (widget.match.video == 1)
          Padding(
            padding: const EdgeInsets.only(left: 8),
            child: Image.asset(
              Utils.getImgPath("live_animation_icon.png"),
              width: 18,
              height: 14,
            ),
          ),
      ],
    );
  }

  Widget bottom() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        QsText(
          '分差 ${widget.match.matchPursueScore}  总分 ${widget.match.matchScore}',
          fontSize: 11,
          color: Colours.grey66,
        ),
      ],
    );
  }

  team(bool isHome) {
    bool isBegin = (widget.match.statusId != 1);
    final position =
        isHome ? widget.match.homePosition : widget.match.awayPosition;
    return Row(
      // mainAxisSize: MainAxisSize.max,
      children: [
        CachedNetworkImage(
          imageUrl: isHome
              ? widget.match.homeLogo ?? ''
              : widget.match.awayLogo ?? '',
          width: 20,
          height: 20,
          placeholder: (context, url) => Styles.placeholderIcon(),
          errorWidget: (context, url, error) =>
              Image.asset(Utils.getImgPath("lq_placeholder.png")),
        ),
        const SizedBox(width: 4),
        Flexible(
          child: QsText(
            isHome ? widget.match.homeName ?? '' : widget.match.awayName ?? '',
            maxLines: 1,
            fontWeight: FontWeight.w500,
            needCenter: true,
            fontSize: 13,
          ),
        ),
        const SizedBox(width: 2),
        if (config.lqList2 == 1) ...[
          QsText(
            position.hasValue == true ? '[$position]' : '',
            fontSize: 11,
            color: Colours.grey99,
          ),
          Container(width: 2)
        ]
      ],
    );
  }

  teamRight() {
    bool isBegin = (widget.match.statusId != 1);
    // (config.lqList1 == 1 && AppConfig.config.showOdds && ModeConfig.matchListOdds
    //     ? teamOdds()
    //     :
    return isBegin
        ? teamScore()
        : Column(
            children: [recent(false), const SizedBox(height: 9), recent(true)],
          );
  }

  teamOdds() {
    List<OddsList>? oddsList = widget.match.oddsList;
    List<List<String>> showList = [];
    if (oddsList != null) {
      oddsList =
          oddsList.where((element) => element.c == config.lqList8).toList();
      if (config.lqList7.contains(0)) {
        List<String> span = [];
        for (OddsList odds in oddsList) {
          if (odds.p == 2001) {
            List<Map<String, dynamic>> jsonList;
            if (config.lqList9 == 0) {
              jsonList = List<Map<String, dynamic>>.from(jsonDecode(odds.o1!));
            } else {
              jsonList = List<Map<String, dynamic>>.from(jsonDecode(odds.o2!));
            }
            span.add(
                jsonList.firstWhere((element) => element['i'] == 'f')['o']!);
            span.add('');
            span.add(' ' +
                jsonList.firstWhere((element) => element['i'] == 's')['o']!);
            showList.add(span);
          }
        }
      }
      if (config.lqList7.contains(1)) {
        List<String> span = [];
        for (OddsList odds in oddsList) {
          if (odds.p == 2002) {
            List<Map<String, dynamic>> jsonList;
            if (config.lqList9 == 0) {
              jsonList = List<Map<String, dynamic>>.from(jsonDecode(odds.o1!));
            } else {
              jsonList = List<Map<String, dynamic>>.from(jsonDecode(odds.o2!));
            }
            span.add(
                jsonList.firstWhere((element) => element['i'] == 'f')['o']!);
            span.add(' ${odds.l ?? ''}');
            span.add(' ' +
                jsonList.firstWhere((element) => element['i'] == 's')['o']!);
            showList.add(span);
          }
        }
      }

      if (config.lqList7.contains(2)) {
        List<String> span = [];
        for (OddsList odds in oddsList) {
          if (odds.p == 2003) {
            List<Map<String, dynamic>> jsonList;
            if (config.lqList9 == 0) {
              jsonList = List<Map<String, dynamic>>.from(jsonDecode(odds.o1!));
            } else {
              jsonList = List<Map<String, dynamic>>.from(jsonDecode(odds.o2!));
            }
            span.add(
                jsonList.firstWhere((element) => element['i'] == 'x')['o']!);
            span.add(
              ' ${odds.l ?? ''}',
            );
            span.add(
                " ${jsonList.firstWhere((element) => element['i'] == 'd')['o']!}");
            showList.add(span);
          }
        }
      }
    }
    // if (showList.length == 1) {
    //   showList.add([]);
    // }
    List<Widget> list = showList
        .map((e) => SizedBox(
              width: 150,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: List.generate(
                    e.length,
                    (index) => QsText(
                          e[index],
                          fontFamily: 'Din',
                          fontSize: 12,
                          color: index == 1 ? Colours.grey66 : Colours.grey99,
                        )),
              ),
            ))
        .toList();
    if (list.length == 2) {
      list.insert(1, const SizedBox(height: 9));
    } else if (list.length == 3) {
      // list.insert(2, const SizedBox(height: 2));
      // list.insert(1, const SizedBox(height: 2));
    }
    return Column(
      children: list,
    );
  }

  teamScore() {
    List<String> score = [];
    List<String> otherScore = [];
    bool ot = (widget.match.needPeriod ?? 0) > (widget.match.periodCount ?? 0);
    int showPeriod =
        ot ? widget.match.needPeriod! - 1 : widget.match.needPeriod!;
    List.generate(showPeriod, (index) {
      if (index == 0) {
        score.add('${widget.match.appMatchScore?.awayOne}');
        otherScore.add('${widget.match.appMatchScore?.homeOne}');
      } else if (index == 1) {
        score.add('${widget.match.appMatchScore?.awayTwo}');
        otherScore.add('${widget.match.appMatchScore?.homeTwo}');
      } else if (index == 2) {
        score.add('${widget.match.appMatchScore?.awayThree}');
        otherScore.add('${widget.match.appMatchScore?.homeThree}');
      } else if (index == 3) {
        score.add('${widget.match.appMatchScore?.awayFour}');
        otherScore.add('${widget.match.appMatchScore?.homeFour}');
      }
    });
    if (ot) {
      score.add('${widget.match.appMatchScore?.awayOt}');
      otherScore.add('${widget.match.appMatchScore?.homeOt}');
    }
    if (widget.match.hasBegin()) {
      score.add('${widget.match.awayScore}');
      otherScore.add('${widget.match.homeScore}');
    }
    score = score.map((e) => e.length <= 1 ? "0$e" : e).toList();
    otherScore = otherScore.map((e) => e.length <= 1 ? "0$e" : e).toList();
    return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
      ...List<Widget>.generate(
          score.length,
          (index) => Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  if (index == score.length - 1) ...[
                    SizedBox(
                      height: 20,
                      child: QsText(
                        score[index],
                        textAlign: TextAlign.end,
                        fontSize: 14,
                        fontFamily: 'Din',
                        color: (score[index].toInt() ?? 0) >
                                (otherScore[index].toInt() ?? 0)
                            ? Colours.main
                            : Colours.redFA9F9F,
                      ).center,
                    ),
                    Container(height: 6),
                    SizedBox(
                      height: 20,
                      child: QsText(
                        otherScore[index],
                        textAlign: TextAlign.end,
                        fontFamily: 'Din',
                        color: (otherScore[index].toInt() ?? 0) >
                                (score[index].toInt() ?? 0)
                            ? Colours.main
                            : Colours.redFA9F9F,
                      ).center,
                    )
                  ] else ...[
                    SizedBox(
                      height: 20,
                      child: QsText(score[index],
                              fontFamily: 'Din',
                              fontSize: 12,
                              color: Colours.grey66)
                          .center,
                    ),
                    Container(height: 6),
                    SizedBox(
                      height: 20,
                      child: QsText(otherScore[index],
                              fontFamily: 'Din',
                              fontSize: 12,
                              color: Colours.grey99)
                          .center,
                    ),
                  ]
                ],
              )).insertEvery(Container(width: 8)),
    ]);
  }

  recent(bool isHome) {
    return QsText(
        isHome
            ? (widget.match.homeInfoRecentRecord.hasValue == true
                ? '近况： ${widget.match.homeInfoRecentRecord}'
                : '')
            : (widget.match.awayInfoRecentRecord.hasValue == true
                ? '近况： ${widget.match.awayInfoRecentRecord}'
                : ''),
        color: Colours.grey66,
        fontSize: 12);
  }

  Widget label(
      {required bool show,
      required String name,
      required Color color,
      String extra = ""}) {
    return !show
        ? Container()
        : GestureDetector(
            onTap: () {
              Utils.onEvent('bspd_djdcbs', params: {"bspd_djdcbs": 0});
              Get.toNamed(Routes.lqMatchDetail,
                  arguments: widget.match.id, parameters: {'tabName': name});
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  margin: const EdgeInsets.only(left: 4),
                  padding: const EdgeInsets.symmetric(horizontal: 2),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2),
                      border: Border.all(color: color, width: 0.5)),
                  child: QsText("$name$extra", fontSize: 10, color: color),
                ),
              ],
            ),
          );
  }
}
